package com.health.db.service.user.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.health.db.dao.sm.IGoodsListDao;
import com.health.db.dao.sm.IGoodsOrderDao;
import com.health.db.dao.user.IGoodsDataUserDao;
import com.health.db.dao.user.IUserAccountLedgerDao;
import com.health.db.dao.user.IUserCardIssueDao;
import com.health.db.dao.user.IUserCardJournalDao;
import com.health.db.dao.user.IUserCardListDao;
import com.health.db.dao.user.IUserCardTypeDao;
import com.health.db.dao.user.IUserLISTDao;
import com.health.db.model.GoodsData;
import com.health.db.model.GoodsDataUser;
import com.health.db.model.GoodsList;
import com.health.db.model.GoodsListCouse;
import com.health.db.model.GoodsListExample;
import com.health.db.model.GoodsOrder;
import com.health.db.model.UserAccountLedger;
import com.health.db.model.UserCardIssue;
import com.health.db.model.UserCardJournal;
import com.health.db.model.UserCardList;
import com.health.db.model.UserCardListExt;
import com.health.db.model.UserCardType;
import com.health.db.model.UserLIST;
import com.health.db.service.user.IUserCardListService;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;

/**
 * 用户卡相关接口实现
 * @author YC
 */
public class UserCardListServiceImpl implements IUserCardListService {

	private IUserCardListDao userCardListDao;
	
	private IUserCardJournalDao userCardJournalDao;
	
	private IUserCardIssueDao  userCardIssueDao;
	
	private IUserAccountLedgerDao userAccountLedgerDao ;
	
	private IUserLISTDao userLISTDao;
	
	private IUserCardTypeDao userCardTypeDao;
	
	private IGoodsListDao goodsListDao ;
	
	private IGoodsDataUserDao goodsDataUserDao;
	
	@Autowired
	private IGoodsOrderDao goodsOrderDao;

	public IGoodsDataUserDao getGoodsDataUserDao() {
		return goodsDataUserDao;
	}

	public void setGoodsDataUserDao(IGoodsDataUserDao goodsDataUserDao) {
		this.goodsDataUserDao = goodsDataUserDao;
	}

	public IGoodsListDao getGoodsListDao() {
		return goodsListDao;
	}

	public void setGoodsListDao(IGoodsListDao goodsListDao) {
		this.goodsListDao = goodsListDao;
	}

	public IUserCardTypeDao getUserCardTypeDao() {
		return userCardTypeDao;
	}

	public void setUserCardTypeDao(IUserCardTypeDao userCardTypeDao) {
		this.userCardTypeDao = userCardTypeDao;
	}

	public IUserLISTDao getUserLISTDao() {
		return userLISTDao;
	}

	public void setUserLISTDao(IUserLISTDao userLISTDao) {
		this.userLISTDao = userLISTDao;
	}

	public IUserAccountLedgerDao getUserAccountLedgerDao() {
		return userAccountLedgerDao;
	}

	public void setUserAccountLedgerDao(IUserAccountLedgerDao userAccountLedgerDao) {
		this.userAccountLedgerDao = userAccountLedgerDao;
	}
	

	public IGoodsOrderDao getGoodsOrderDao() {
		return goodsOrderDao;
	}

	public void setGoodsOrderDao(IGoodsOrderDao goodsOrderDao) {
		this.goodsOrderDao = goodsOrderDao;
	}

	/**
	 * @return the userCardIssueDao
	 */
	public IUserCardIssueDao getUserCardIssueDao() {
		return userCardIssueDao;
	}

	/**
	 * @param userCardIssueDao the userCardIssueDao to set
	 */
	public void setUserCardIssueDao(IUserCardIssueDao userCardIssueDao) {
		this.userCardIssueDao = userCardIssueDao;
	}

	/**
	 * @return the userCardListDao
	 */
	public IUserCardListDao getUserCardListDao() {
		return userCardListDao;
	}

	/**
	 * @param userCardListDao the userCardListDao to set
	 */
	public void setUserCardListDao(IUserCardListDao userCardListDao) {
		this.userCardListDao = userCardListDao;
	}

	/**
	 * 按照cardId查询卡数据
	 * @param cardId卡号
	 */
	@Override
	public UserCardList  selectByCardId(Long cardId) {
		
		UserCardListExt example = new UserCardListExt();
		example.setCardid(cardId);
		
		List<UserCardList> list = userCardListDao.selectUserCardLists(example);
		//返回第一个符合规则的数据
		if (list.size()>0) {
			return  list.get(0);
		}else{
			return null;
		}
		
	}

	/**
	 * 插入卡日志信息
	 * @param record 卡对象
	 */
	@Override
	public int insertUserCardJournal(UserCardJournal record) {
		// TODO Auto-generated method stub
		return userCardJournalDao.insert(record);
	}

	/**
	 * @return the userCardJournalDao
	 */
	public IUserCardJournalDao getUserCardJournalDao() {
		return userCardJournalDao;
	}

	/**
	 * @param userCardJournalDao the userCardJournalDao to set
	 */
	public void setUserCardJournalDao(IUserCardJournalDao userCardJournalDao) {
		this.userCardJournalDao = userCardJournalDao;
	}

	@Override
	public List<UserCardList> selectUserCardLists(UserCardListExt example) {
		// TODO Auto-generated method stub
		return userCardListDao.selectUserCardLists(example);
	}

	@Override
	public UserCardIssue selectUserCardIssueByPasword(String password) {
		// TODO Auto-generated method stub
		return userCardIssueDao.selectByPasword(password);
	}
	
	
	@Override
	public int activeUserCardByRecharge(Long userId,Long cardTypeId ) {
		// TODO Auto-generated method stub
		int updateFlag = -1;
		UserCardType userCardType = userCardTypeDao.selectByCardTypeId(cardTypeId);
		
		if (null!=userCardType) {
		
		UserCardList userCardList = new UserCardList();
		
		//卡资源表中的数据迁移
		int x=(int)(Math.random()*100);
		
		if (x<10) {
			userCardList.setCardIdno("RE"+String.valueOf(DateUtils.millis())+"0"+String.valueOf(x));
		}else{
			userCardList.setCardIdno("RE"+String.valueOf(DateUtils.millis())+String.valueOf(x));
		}

		userCardList.setCardtypeid(cardTypeId.intValue());
		userCardList.setCardName(userCardType.getCardName());
		userCardList.setOwnerid(userId);
		userCardList.setPassword("");
		userCardList.setIsUsedFlag((short)1);
		//自动生成
		userCardList.setComment(String.valueOf(userId.longValue()));
		//卡类型表中的数据迁移
		userCardList.setCardtime01(userCardType.getCardtime01());
		userCardList.setLefttime01(userCardType.getCardtime01());
		userCardList.setCardtime02(userCardType.getCardtime02());
		userCardList.setLefttime02(userCardType.getCardtime02());
		userCardList.setCardtime03(userCardType.getCardtime03());
		userCardList.setLefttime03(userCardType.getCardtime03());
		userCardList.setCardtime04(userCardType.getCardtime04());
		userCardList.setLefttime04(userCardType.getCardtime04());
		userCardList.setCardtime05(userCardType.getCardtime05());
		userCardList.setLefttime05(userCardType.getCardtime05());
		
		Date now = DateUtils.now();
		userCardList.setActivateDate(now);
		//多少天后失效
		userCardList.setFailureDate(DateUtils.getDateAfter(now,Integer.valueOf(userCardType.getValidDuration())));
		//时间
		userCardList.setCreateDate(now);
		userCardList.setUpdateDate(now);
		
		userCardListDao.insertNoCardId(userCardList);
		}
		return updateFlag;
	}
	
	@Override
	public int activeVIPUserCard(Long userId,UserCardIssue issue) {
		// TODO Auto-generated method stub
		Long goodsId = Long.valueOf(issue.getCardtypeid());
		//GoodsDataExample example = new GoodsDataExample();
		//example.setGoodsid(record.getGoodsid());
		GoodsList goods = goodsListDao.selectGoodsAndDatasByGoodsId(goodsId);
		//查看下属产品列表
		List<GoodsData> goodsList = goods.getGoodsDataList();
		if (null==goods||null==goodsList) {
			return -2;
		}
	
		List<GoodsDataUser> list = new ArrayList<GoodsDataUser>();
		Date now =DateUtils.now();
		UserLIST userLIST= userLISTDao.selectByUserId(userId);
		if (null!=userLIST.getVipLevel()&&null!=userLIST.getVipEndDate()) {
			
			if (userLIST.getVipEndDate().compareTo(DateUtils.now())>0) {
				now = userLIST.getVipEndDate();
			}
		}
		
		for (int i = 0; i < goodsList.size(); i++) {
			
			GoodsData goodsDataTemp = goodsList.get(i);

		    String validDuration= goodsDataTemp.getValidDuration();

		    String frequency = goodsDataTemp.getFrequency();
			
			Byte rechargeFlag = goodsDataTemp.getRechargeFlag();
			
			if (null!=rechargeFlag&&rechargeFlag.intValue()==1) {
				UserCardList userCardList =activeUserCardByRecharge( goodsDataTemp , userId, goodsId ) ;
				userCardListDao.insertNoCardId(userCardList);
				
			}else if (StringUtils.isNotBlank(validDuration)&&StringUtils.isNotBlank(frequency)
				&&	!validDuration.equals(frequency)) 
			{
				int validDurationInt= Integer.valueOf(validDuration);
				int frequencyInt= Integer.valueOf(frequency);
				
				do {
					
					GoodsDataUser goodsDataListTemp =new GoodsDataUser();
					goodsDataListTemp.setItemValue(goodsDataTemp.getItemValue());
					goodsDataListTemp.setItemName(goodsDataTemp.getItemName());
					goodsDataListTemp.setGoodsid(goodsId);
					goodsDataListTemp.setOwnerId(userId);
					goodsDataListTemp.setUpdateDate(now);
					goodsDataListTemp.setGoodsDataId(goodsDataTemp.getRecid());
					goodsDataListTemp.setFailureDate(DateUtils.getMonthAfter(now, frequencyInt));
					goodsDataListTemp.setActivateDate(DateUtils.getMonthAfter(goodsDataListTemp.getFailureDate(), -Integer.valueOf(frequency)));
					goodsDataListTemp.setOwnerName(userLIST.getUserName());
					goodsDataListTemp.setOperFlag((byte) 0);
					frequencyInt=frequencyInt+Integer.valueOf(frequency);
					list.add(goodsDataListTemp);
					
				} while (frequencyInt<=validDurationInt);
				
			}else{
				
				GoodsDataUser goodsDataListTemp =new GoodsDataUser();
				goodsDataListTemp.setItemValue(goodsDataTemp.getItemValue());
				goodsDataListTemp.setItemName(goodsDataTemp.getItemName());
				goodsDataListTemp.setGoodsid(goodsId);
				goodsDataListTemp.setOwnerId(userId);
				goodsDataListTemp.setUpdateDate(now);
				goodsDataListTemp.setGoodsDataId(goodsDataTemp.getRecid());
				goodsDataListTemp.setOwnerName(userLIST.getUserName());
				goodsDataListTemp.setOperFlag((byte) 0);
				if (StringUtils.isNotBlank(validDuration)) {
					goodsDataListTemp.setFailureDate(DateUtils.getMonthAfter(now, Integer.valueOf(validDuration)));
					goodsDataListTemp.setActivateDate(now);
				}else{
					goodsDataListTemp.setFailureDate(DateUtils.getMonthAfter(now, 12));
					goodsDataListTemp.setActivateDate(now);
				}
				list.add(goodsDataListTemp);
			}
		}
		
		userLIST.setVipLevel(goods.getLevel());
		userLIST.setVipStartDate(null==userLIST.getVipStartDate()?DateUtils.now():userLIST.getVipStartDate());
		userLIST.setVipEndDate(DateUtils.getMonthAfter(now, Integer.valueOf(goodsList.get(0).getValidDuration())));
			
		
		//设置卡更新
		UserCardIssue issueForupdate = new UserCardIssue();
		issueForupdate.setCardid(issue.getCardid());
		issueForupdate.setActivateDate(now);
		issueForupdate.setFailureDate(userLIST.getVipEndDate());
		issueForupdate.setOwnerid(userId);
		issueForupdate.setOwnerName(userLIST.getUserName());
		issueForupdate.setPassword(issue.getPassword());
		
		userCardIssueDao.updateBySelective(issueForupdate);
		
		goodsDataUserDao.insertBatch(list);
		userLISTDao.updateByPrimaryKey(userLIST);
		return 1;
		
	}
	
	
	
	public UserCardList activeUserCardByRecharge(GoodsData goodsDataTemp ,Long userId,Long cardTypeId ) {
		// TODO Auto-generated method stub
		
		UserCardList userCardList = new UserCardList();
		
		//卡资源表中的数据迁移
		int x=(int)(Math.random()*100);
		userCardList.setCardIdno("VIP"+String.valueOf(DateUtils.millis())+String.valueOf(x));
		userCardList.setCardtypeid(cardTypeId.intValue());
		userCardList.setCardName(goodsDataTemp.getItemName());
		userCardList.setOwnerid(userId);
		userCardList.setPassword("");
		userCardList.setIsUsedFlag((short)1);
		//自动生成
		userCardList.setComment("1");
		//卡类型表中的数据迁移
		userCardList.setCardtime02(new BigDecimal( goodsDataTemp.getItemValue()));
		userCardList.setLefttime02(new BigDecimal(goodsDataTemp.getItemValue()));
		
		Date now = DateUtils.now();
		userCardList.setActivateDate(now);
		//多少天后失效
		userCardList.setFailureDate(DateUtils.getMonthAfter(now, Integer.valueOf(goodsDataTemp.getValidDuration())));
		//时间
		userCardList.setCreateDate(now);
		userCardList.setUpdateDate(now);
		
		
		return userCardList;
	}
	
	
	@Override
	public int activeUserCardByPasword(Long userId,UserCardIssue issue) {
		// TODO Auto-generated method stub
		int updateFlag = -1;
		
		UserCardList userCardList = new UserCardList();
		
		//卡资源表中的数据迁移
		//userCardList.setCardid();
		userCardList.setCardIdno(issue.getCardIdno());
		userCardList.setCardtypeid(issue.getCardtypeid());
		userCardList.setCardName(issue.getCardName());
		userCardList.setOwnerid(userId);
		userCardList.setPassword(issue.getPassword());
		userCardList.setIsUsedFlag(issue.getIsUsedFlag());
		UserCardType userCardType = issue.getUserCardType();
		userCardList.setComment(String.valueOf(issue.getCardid().longValue()));
		//卡类型表中的数据迁移
		userCardList.setCardtime01(userCardType.getCardtime01());
		userCardList.setLefttime01(userCardType.getCardtime01());
		userCardList.setCardtime02(userCardType.getCardtime02());
		userCardList.setLefttime02(userCardType.getCardtime02());
		userCardList.setCardtime03(userCardType.getCardtime03());
		userCardList.setLefttime03(userCardType.getCardtime03());
		userCardList.setCardtime04(userCardType.getCardtime04());
		userCardList.setLefttime04(userCardType.getCardtime04());
		userCardList.setCardtime05(userCardType.getCardtime05());
		userCardList.setLefttime05(userCardType.getCardtime05());
		
		Date now = DateUtils.now();
		
		userCardList.setActivateDate(now);
		//多少天后失效
		userCardList.setFailureDate(DateUtils.getDateAfter(now,Integer.valueOf(userCardType.getValidDuration())));
		//时间
		userCardList.setCreateDate(now);
		userCardList.setUpdateDate(now);
		
		UserCardIssue issueForupdate = new UserCardIssue();
		issueForupdate.setCardid(issue.getCardid());
		issueForupdate.setActivateDate(userCardList.getActivateDate());
		issueForupdate.setFailureDate(userCardList.getFailureDate());
		issueForupdate.setOwnerid(userId);
		issueForupdate.setPassword(issue.getPassword());
		
		userCardListDao.insertNoCardId(userCardList);
		
		userCardIssueDao.updateBySelective(issueForupdate);
		
		return updateFlag;
	}
	 
	@Override
	public int activeRechargeCardByPasword(Long userId,UserCardIssue issue){
		int updateFlag = -1;
			
		UserCardType userCardType = issue.getUserCardType();
		Date now = DateUtils.now();
			
		UserCardIssue issueForupdate = new UserCardIssue();
		issueForupdate.setCardid(issue.getCardid());
		issueForupdate.setActivateDate(now);
		issueForupdate.setFailureDate(DateUtils.getDateAfter(now,Integer.valueOf(userCardType.getValidDuration())));
		issueForupdate.setOwnerid(userId);
		
		userCardIssueDao.updateBySelective(issueForupdate);    
		 
		UserAccountLedger accountLedge = userAccountLedgerDao.selectByUserId(userId);
		
		if (null!=accountLedge) {
			accountLedge.setBalanceTotal(accountLedge.getBalanceTotal().add(userCardType.getCardtime02()));
			userAccountLedgerDao.updateBalance(accountLedge);
		}
	    else{
			accountLedge = new UserAccountLedger();
			
			accountLedge.setBalanceTotal(userCardType.getCardtime02());
			
			accountLedge.setAccountid(userId);
			accountLedge.setIsUsedFlag((short) 1);
			accountLedge.setColumnid(2);
			UserLIST userLIST = userLISTDao.selectByUserId(userId);
			accountLedge.setAccountIdno(userLIST.getUserNo());
			accountLedge.setAccountName(userLIST.getUserName());
			accountLedge.setCreateUserid(userId);
			accountLedge.setUpdateUserid(userId);
			userAccountLedgerDao.insertAccountLedger(accountLedge);
		 }
		
		 return updateFlag;
	 }

	/**
	 * 激活卡用户
	 * @param userId 用户id
	 * @param issue  卡对象
	 * 暂未处理重复购买
	 */
	@Override
	public int activeCourseCard(Long userId, UserCardIssue issue) {
		// TODO Auto-generated method stub
		
		int updateFlag = -1;
		//卡类型->对应商品id
		Long goodsId =  Long.valueOf(issue.getUserCardType().getGoodsId());
		
		//Long goodsId = Long.valueOf(issue.getCardtypeid());
		GoodsOrder goodsOrder = new GoodsOrder();
		
		GoodsListExample example = new GoodsListExample();
		example.setGoodsid(Long.valueOf(goodsId));
		
		//查询商品对象
		List<GoodsListCouse> list =  goodsListDao.selectBySimpleCouse(example);
		if (list.size()==1) {
			GoodsListCouse temp = list.get(0);
			//查看课程
			if (Integer.valueOf(temp.getTypeId()).intValue() != Constant.CONSTANTS_PAY_ACTION_ID_61.intValue()) {
				return -3;
			}
			
			//预处理商品对象
			goodsOrder.setGoodsName(temp.getGoodsName());
			goodsOrder.setGoodsType(temp.getTypeId());
			goodsOrder.setGoodsMeasure(temp.getGoodsMeasure());
			goodsOrder.setTotal(new BigDecimal(temp.getSalePrice()));
	
		}else{
			 return updateFlag;
		}
		
		UserCardType userCardType = issue.getUserCardType();
		Date now = DateUtils.now();
		
		//更新卡源表
		UserCardIssue issueForupdate = new UserCardIssue();
		issueForupdate.setCardid(issue.getCardid());
		issueForupdate.setActivateDate(now);
		issueForupdate.setFailureDate(DateUtils.getDateAfter(now,Integer.valueOf(userCardType.getValidDuration())));
		issueForupdate.setOwnerid(userId);
		
		updateFlag =userCardIssueDao.updateBySelective(issueForupdate);    
		
		//插入订单表
		goodsOrder.setOwnerid(Long.valueOf(userId));
		goodsOrder.setGoodsid(goodsId);
		//goodsOrder.setOwenerName(req.getUserName());
		//已支付
		goodsOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5);
		goodsOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
		goodsOrder.setPayFlag(String.valueOf(Constant.CONSTANTS_IS_PAYMENT_FALSE));
		goodsOrder.setPayTypeId(Constant.CONSTANTS_IS_PAYMENT_FALSE);
		goodsOrder.setRefBillid(issue.getCardid());
		
		goodsOrderDao.insert(goodsOrder);
		
		return updateFlag;
		
	}
	
}
